package com.neusoft.elmboot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neusoft.elmboot.exception.exceptions.BaseException;
import com.neusoft.elmboot.exception.exceptions.ErrorStateException;
import com.neusoft.elmboot.mapper.WalletRuleMapper;
import com.neusoft.elmboot.po.wallet.WalletRule;
import com.neusoft.elmboot.service.WalletRuleService;
import jakarta.annotation.Resource;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
@Transactional(rollbackFor = Exception.class)
public class WalletRuleServiceImpl extends ServiceImpl<WalletRuleMapper, WalletRule> implements WalletRuleService {
    
    @Resource
    private WalletRuleMapper walletRuleMapper;
    
    private static final String RECHARGE_RULE_TYPE = "recharge";
    private static final String WITHDRAW_RULE_TYPE = "withdraw";
    
    @Override
    public WalletRule getRechargeRule() throws BaseException {
        try {
            WalletRule rule = walletRuleMapper.selectById(RECHARGE_RULE_TYPE);
            if (rule == null) {
                // 如果不存在，创建默认规则
                rule = createDefaultRechargeRule();
            }
            return rule;
        } catch (DataAccessException e) {
            // 如果表不存在，抛出更友好的错误信息
            String errorMsg = e.getMessage();
            if (e.getCause() != null && e.getCause().getMessage() != null) {
                errorMsg = e.getCause().getMessage();
            }
            if (errorMsg != null && errorMsg.contains("doesn't exist")) {
                throw new ErrorStateException("数据库表 wallet_rule 不存在，请先执行 create_wallet_rule_table.sql 脚本创建表");
            }
            throw new ErrorStateException("获取充值规则失败：" + errorMsg);
        }
    }
    
    @Override
    public WalletRule getWithdrawRule() throws BaseException {
        try {
            WalletRule rule = walletRuleMapper.selectById(WITHDRAW_RULE_TYPE);
            if (rule == null) {
                // 如果不存在，创建默认规则
                rule = createDefaultWithdrawRule();
            }
            return rule;
        } catch (DataAccessException e) {
            // 如果表不存在，抛出更友好的错误信息
            String errorMsg = e.getMessage();
            if (e.getCause() != null && e.getCause().getMessage() != null) {
                errorMsg = e.getCause().getMessage();
            }
            if (errorMsg != null && errorMsg.contains("doesn't exist")) {
                throw new ErrorStateException("数据库表 wallet_rule 不存在，请先执行 create_wallet_rule_table.sql 脚本创建表");
            }
            throw new ErrorStateException("获取提现规则失败：" + errorMsg);
        }
    }
    
    @Override
    public void updateRechargeRule(BigDecimal rechargeLevel, BigDecimal rechargeGift) throws BaseException {
        WalletRule rule = walletRuleMapper.selectById(RECHARGE_RULE_TYPE);
        if (rule == null) {
            rule = new WalletRule();
            rule.setRuleType(RECHARGE_RULE_TYPE);
            rule.setCreateTime(LocalDateTime.now());
        }
        rule.setRechargeLevel(rechargeLevel);
        rule.setRechargeGift(rechargeGift);
        rule.setUpdateTime(LocalDateTime.now());
        
        if (rule.getCreateTime() == null) {
            walletRuleMapper.insert(rule);
        } else {
            walletRuleMapper.updateById(rule);
        }
    }
    
    @Override
    public void updateWithdrawRule(BigDecimal withdrawRate) throws BaseException {
        WalletRule rule = walletRuleMapper.selectById(WITHDRAW_RULE_TYPE);
        if (rule == null) {
            rule = new WalletRule();
            rule.setRuleType(WITHDRAW_RULE_TYPE);
            rule.setCreateTime(LocalDateTime.now());
        }
        rule.setWithdrawRate(withdrawRate);
        rule.setUpdateTime(LocalDateTime.now());
        
        if (rule.getCreateTime() == null) {
            walletRuleMapper.insert(rule);
        } else {
            walletRuleMapper.updateById(rule);
        }
    }
    
    @Override
    public void updateOverdraftRule(BigDecimal dailyInterestRate, 
                                   BigDecimal minOverdraftAmount, 
                                   BigDecimal maxOverdraftAmount) throws BaseException {
        // 透支规则可以存储在充值或提现规则中，这里使用充值规则
        WalletRule rule = walletRuleMapper.selectById(RECHARGE_RULE_TYPE);
        if (rule == null) {
            rule = createDefaultRechargeRule();
        }
        rule.setDailyInterestRate(dailyInterestRate);
        rule.setMinOverdraftAmount(minOverdraftAmount);
        rule.setMaxOverdraftAmount(maxOverdraftAmount);
        rule.setUpdateTime(LocalDateTime.now());
        walletRuleMapper.updateById(rule);
    }
    
    private WalletRule createDefaultRechargeRule() throws BaseException {
        try {
            WalletRule rule = new WalletRule();
            rule.setRuleType(RECHARGE_RULE_TYPE);
            rule.setRechargeLevel(BigDecimal.valueOf(1000));
            rule.setRechargeGift(BigDecimal.valueOf(100));
            rule.setDailyInterestRate(BigDecimal.valueOf(0.001));
            rule.setMinOverdraftAmount(BigDecimal.valueOf(100));
            rule.setMaxOverdraftAmount(BigDecimal.valueOf(1000));
            rule.setCreateTime(LocalDateTime.now());
            rule.setUpdateTime(LocalDateTime.now());
            walletRuleMapper.insert(rule);
            return rule;
        } catch (DataAccessException e) {
            String errorMsg = e.getMessage();
            if (e.getCause() != null && e.getCause().getMessage() != null) {
                errorMsg = e.getCause().getMessage();
            }
            if (errorMsg != null && errorMsg.contains("doesn't exist")) {
                throw new ErrorStateException("数据库表 wallet_rule 不存在，请先执行 create_wallet_rule_table.sql 脚本创建表");
            }
            throw new ErrorStateException("创建默认充值规则失败：" + errorMsg);
        }
    }
    
    private WalletRule createDefaultWithdrawRule() throws BaseException {
        try {
            WalletRule rule = new WalletRule();
            rule.setRuleType(WITHDRAW_RULE_TYPE);
            rule.setWithdrawRate(BigDecimal.valueOf(0.9)); // 90%，即扣除10%手续费
            rule.setCreateTime(LocalDateTime.now());
            rule.setUpdateTime(LocalDateTime.now());
            walletRuleMapper.insert(rule);
            return rule;
        } catch (DataAccessException e) {
            String errorMsg = e.getMessage();
            if (e.getCause() != null && e.getCause().getMessage() != null) {
                errorMsg = e.getCause().getMessage();
            }
            if (errorMsg != null && errorMsg.contains("doesn't exist")) {
                throw new ErrorStateException("数据库表 wallet_rule 不存在，请先执行 create_wallet_rule_table.sql 脚本创建表");
            }
            throw new ErrorStateException("创建默认提现规则失败：" + errorMsg);
        }
    }
}

